package com.quktzhuanka.app.fragments;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.reflect.TypeToken;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.UiError;
import com.quktzhuanka.app.R;
import com.quktzhuanka.app.adapter.BkAdapter;
import com.quktzhuanka.app.adapter.SuCaiAdapter;
import com.quktzhuanka.app.adapter.XtAdapter;
import com.quktzhuanka.app.base.BaseLazyFragment;
import com.quktzhuanka.app.bean.BkBean;
import com.quktzhuanka.app.bean.MessageCenterBean;
import com.quktzhuanka.app.bean.MessageEvent;
import com.quktzhuanka.app.bean.Response;
import com.quktzhuanka.app.bean.SuCaiBean;
import com.quktzhuanka.app.config.Constants;
import com.quktzhuanka.app.https.HttpUtils;
import com.quktzhuanka.app.https.onOKJsonHttpResponseHandler;
import com.quktzhuanka.app.utils.WxUtil;
import com.quktzhuanka.app.widget.indicator.MagicIndicator;
import com.quktzhuanka.app.widget.indicator.ViewPagerHelper;
import com.quktzhuanka.app.widget.indicator.buildins.commonnavigator.CommonNavigator;
import com.quktzhuanka.app.widget.indicator.buildins.commonnavigator.abs.CommonNavigatorAdapter;
import com.quktzhuanka.app.widget.indicator.buildins.commonnavigator.abs.IPagerIndicator;
import com.quktzhuanka.app.widget.indicator.buildins.commonnavigator.abs.IPagerTitleView;
import com.quktzhuanka.app.widget.indicator.buildins.commonnavigator.indicators.LinePagerIndicator;
import com.quktzhuanka.app.widget.indicator.buildins.commonnavigator.titles.CommonPagerTitleView;
import com.quktzhuanka.app.wmm.QQShareUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cz.msebera.android.httpclient.Header;

public class CommuitityFragment extends BaseLazyFragment {
    @BindView(R.id.magic_indicator)
    MagicIndicator tabBar;
    @BindView(R.id.view_page)
    ViewPager viewpager;
    @BindView(R.id.view_zz)
    View viewZz;
    @BindView(R.id.copy_friends_cicle_btn)
    TextView copyFriendsCicleBtn;
    @BindView(R.id.copy_friends_btn)
    TextView copyFriendsBtn;
    @BindView(R.id.ll_share)
    LinearLayout llShare;
    @BindView(R.id.copy_friends_qq)
    TextView copyFriendsQq;
    @BindView(R.id.copy_friends_cicle_zone)
    TextView copyFriendsCicleZone;

    @BindView(R.id.tv_left)
    TextView tvLeft;
    @BindView(R.id.tv_title)
    TextView tvTitle;


    private View view;
    private ArrayList<String> list = new ArrayList<>();
    private int index = 0;
    private List<View> views = new ArrayList<>();
    private RecyclerView left_recyview, right_recyview,xt_recyview;
    private SmartRefreshLayout left_refresh, right_refresh,xt_refresh;
    private int leftPage = 1, rightPage = 1,xuetangPage=1;
    private List<BkBean.BKItem> leftList = new ArrayList<>();
    private List<SuCaiBean> rightList = new ArrayList<>();
    private SuCaiAdapter rightAdapter;
    private BkAdapter leftAdapter;
    private XtAdapter xtAdapter;
    private List<MessageCenterBean.MessageCenterChildBean> xtlist = new ArrayList<>();
    SuCaiBean item;
    private  ArrayList<String> shareList=new ArrayList<>();
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_shequ, container, false);
        ButterKnife.bind(this, view);
        init();
        addListener();
        EventBus.getDefault().register(this);
        return view;
    }

    private void init() {
        tvTitle.setText("社区");
        list.add("每日爆款");
        list.add("宣传素材");
        list.add("赚咖联盟学堂");
        LinearLayout linearLayout = (LinearLayout) LayoutInflater.from(context).inflate(R.layout.layout_shequ, null);
        left_refresh = linearLayout.findViewById(R.id.refresh_layout);
        left_recyview = linearLayout.findViewById(R.id.commuitity_list);
        LinearLayoutManager tmp = new LinearLayoutManager(context);
        tmp.setOrientation(LinearLayoutManager.VERTICAL);
        left_recyview = linearLayout.findViewById(R.id.commuitity_list);
        left_recyview.setLayoutManager(tmp);
        leftAdapter = new BkAdapter(context, R.layout.item_shequ, leftList);
        left_recyview.setAdapter(leftAdapter);
        views.add(linearLayout);
        //宣传素材
        LinearLayout linearLayout2 = (LinearLayout) LayoutInflater.from(context).inflate(R.layout.layout_shequ, null);
        right_refresh = linearLayout2.findViewById(R.id.refresh_layout);
        LinearLayoutManager tmp2 = new LinearLayoutManager(context);
        tmp2.setOrientation(LinearLayoutManager.VERTICAL);
        right_recyview = linearLayout2.findViewById(R.id.commuitity_list);
        right_recyview.setLayoutManager(tmp2);
        rightAdapter = new SuCaiAdapter(context, R.layout.item_shequ, rightList);
        right_recyview.setAdapter(rightAdapter);
        views.add(linearLayout2);
        //学堂
        LinearLayout linearLayout3 = (LinearLayout) LayoutInflater.from(context).inflate(R.layout.layout_shequ, null);
        xt_refresh = linearLayout3.findViewById(R.id.refresh_layout);
        LinearLayoutManager tmp3 = new LinearLayoutManager(context);
        tmp3.setOrientation(LinearLayoutManager.VERTICAL);
        xt_recyview = linearLayout3.findViewById(R.id.commuitity_list);
        xt_recyview.setLayoutManager(tmp3);
        xtAdapter = new XtAdapter(context, R.layout.item_xt, xtlist);
        xt_recyview.setAdapter(xtAdapter);
        views.add(linearLayout3);
        viewpager.setAdapter(pagerAdapter);
        CommonNavigator commonNavigator = new CommonNavigator(context);
        commonNavigator.setSkimOver(true);
        commonNavigator.setAdapter(new CommonNavigatorAdapter() {

            @Override
            public int getCount() {
                return list.size();
            }

            @Override
            public IPagerTitleView getTitleView(final Context context, final int index) {
                CommonPagerTitleView commonPagerTitleView = new CommonPagerTitleView(context);
                commonPagerTitleView.setContentView(R.layout.item_text2);
                final TextView titleText = commonPagerTitleView.findViewById(R.id.txt_cat);
//                final TextView txt_cat_b = commonPagerTitleView.findViewById(R.id.txt_cat_b);
                titleText.setText(list.get(index));
                commonPagerTitleView.setOnPagerTitleChangeListener(new CommonPagerTitleView.OnPagerTitleChangeListener() {

                    @Override
                    public void onDeselected(int i, int i1) {
                        titleText.setTextColor(getResources().getColor(R.color.col_666));
//                        txt_cat_b.setBackgroundColor(getResources().getColor(R.color.white));
//                        titleText.setBackgroundResource(R.mipmap.ic_select_b1);

                    }
                    @Override
                    public void onSelected(int i, int i1) {
                        titleText.setTextColor(getResources().getColor(R.color.blue_1));
//                        txt_cat_b.setBackgroundColor(getResources().getColor(R.color.blue_1));
//                        titleText.setBackgroundResource(R.mipmap.ic_select_b);
                    }
                    @Override
                    public void onEnter(int i, int i1, float v, boolean b) {
                    }
                    @Override
                    public void onLeave(int i, int i1, float v, boolean b) {

                    }
                });

                commonPagerTitleView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        viewpager.setCurrentItem(index);
                    }
                });
                return commonPagerTitleView;
            }

            @Override
            public IPagerIndicator getIndicator(Context context) {
                LinePagerIndicator indicator = new LinePagerIndicator(context);
                indicator.setMode(1);
                indicator.setColors(getResources().getColor(R.color.blue_1));
                return indicator;
            }
        });
        tabBar.setNavigator(commonNavigator);
        ViewPagerHelper.bind(tabBar, viewpager);
        //设置页数
        viewpager.setCurrentItem(index);
        left_refresh.autoRefresh();
        right_refresh.autoRefresh();
        xt_refresh.autoRefresh();
    }

    private void addListener() {
        left_refresh.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                leftPage++;
                getLeftList();
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                leftPage = 1;
                getLeftList();
            }
        });
        right_refresh.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                rightPage++;
                getRightList();
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                rightPage = 1;
                getRightList();
            }
        });
        xt_refresh.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                xuetangPage++;
                getXt();
            };

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                xuetangPage = 1;
                getXt();
            }
        });
        viewZz.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                viewZz.setVisibility(View.GONE);
                llShare.setVisibility(View.GONE);
            }
        });
        copyFriendsBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (item == null) {
                    return;
                }
                RequestParams requestParams = new RequestParams();
                requestParams.put("id", item.getId());
                HttpUtils.post(Constants.UPDATE_SHARE_NUM, requestParams, new TextHttpResponseHandler() {
                    @Override
                    public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                    }

                    @Override
                    public void onSuccess(int statusCode, Header[] headers, String responseString) {
                    }
                });
                WxUtil.sharePicByBitMap2(shareList.size() > 0 ? shareList.get(0) : "", "pyq", SendMessageToWX.Req.WXSceneSession, context, item.getMob_text());
                viewZz.performClick();
            }
        });
        copyFriendsCicleBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (item == null) {
                    return;
                }
                RequestParams requestParams = new RequestParams();
                requestParams.put("id", item.getId());
                HttpUtils.post(Constants.UPDATE_SHARE_NUM, requestParams, new TextHttpResponseHandler() {
                    @Override
                    public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                    }

                    @Override
                    public void onSuccess(int statusCode, Header[] headers, String responseString) {
                    }
                });
                WxUtil.sharePicByBitMap2(shareList.size() > 0 ? shareList.get(0) : "", "pyq", SendMessageToWX.Req.WXSceneTimeline, context, item.getMob_text());
                viewZz.performClick();
            }
        });
        copyFriendsQq.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (item == null) {
                    return;
                }
                RequestParams requestParams = new RequestParams();
                requestParams.put("id", item.getId());
                HttpUtils.post(Constants.UPDATE_SHARE_NUM, requestParams, new TextHttpResponseHandler() {
                    @Override
                    public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                    }

                    @Override
                    public void onSuccess(int statusCode, Header[] headers, String responseString) {
                    }
                });
                QQShareUtil.shareToQQ(item.getTitle(), item.getMob_text(), shareList, getActivity(), new IUiListener() {
                    @Override
                    public void onComplete(Object o) {

                    }

                    @Override
                    public void onError(UiError uiError) {
                        Log.d("dfsdf",uiError.errorMessage);
                    }

                    @Override
                    public void onCancel() {

                    }
                });
                viewZz.performClick();
            }
        });
        /**
         * 分享次数
         */
        copyFriendsCicleZone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (item == null) {
                    return;
                }
                RequestParams requestParams = new RequestParams();
                requestParams.put("id", item.getId());
                HttpUtils.post(Constants.UPDATE_SHARE_NUM, requestParams, new TextHttpResponseHandler() {
                    @Override
                    public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                    }

                    @Override
                    public void onSuccess(int statusCode, Header[] headers, String responseString) {
                    }
                });
                QQShareUtil.shareToQZone(shareList, item.getTitle(), item.getMob_text(), getActivity(), new IUiListener() {
                    @Override
                    public void onComplete(Object o) {

                    }

                    @Override
                    public void onError(UiError uiError) {
                    }

                    @Override
                    public void onCancel() {

                    }
                });
                viewZz.performClick();
            }
        });
    }

    /**
     * 赚咖联盟学堂
     */
    private void getXt(){
        RequestParams requestParams = new RequestParams();
        requestParams.put("cat_id", 5);
        requestParams.put("p", xuetangPage);
        requestParams.put("per", 8);
        HttpUtils.post(Constants.MESSAGE_ARTICLE_GETARTICLELIST_URL , requestParams, new onOKJsonHttpResponseHandler<MessageCenterBean>(new TypeToken<Response<MessageCenterBean>>() {
        }) {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                showToast(throwable.getMessage());
            }

            @Override
            public void onSuccess(int statusCode, Response<MessageCenterBean> datas) {
                if (datas.isSuccess()) {
                    if (xuetangPage == 1) {
                        xtlist.clear();
                        xtlist.addAll(datas.getData().getList());
                        xt_refresh.finishRefresh();
                    } else {
                        if (datas.getData().getList().size() <= 0) {
                            showToast("已加载全部");
                            xuetangPage--;
                        }
                        xtlist.addAll(datas.getData().getList());
                        xt_refresh.finishLoadMore();
                    }
                    xtAdapter.notifyDataSetChanged();
                } else {
                    showToast(datas.getMsg());
                }
            }
        });
    }

    /**
     *
     */
    private void getLeftList() {
        RequestParams requestParams = new RequestParams();
        requestParams.put("p", leftPage);
        requestParams.put("per", 6);
        HttpUtils.post(Constants.GETBK_NEW, requestParams, new onOKJsonHttpResponseHandler<BkBean>(new TypeToken<Response<BkBean>>() {
        }) {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                showToast(throwable.getMessage());
            }

            @Override
            public void onSuccess(int statusCode, Response<BkBean> datas) {
                if (datas.isSuccess()) {
                    if (leftPage == 1) {
                        leftList.clear();
                        leftList.addAll(datas.getData().list);
                        left_refresh.finishRefresh();
                    } else {
                        if (datas.getData().list.size() <= 0) {
                            showToast("已加载全部");
                            leftPage--;
                        }
                        leftList.addAll(datas.getData().list);
                        left_refresh.finishLoadMore();
                    }
                    leftAdapter.notifyDataSetChanged();
                } else {
                    showToast(datas.getMsg());
                }
            }
        });
    }

    /**
     * 宣传素材
     */
    private void getRightList() {
        RequestParams requestParams = new RequestParams();
        requestParams.put("p", rightPage);
        requestParams.put("per", 6);
        requestParams.put("board_id", 2);
        HttpUtils.post(Constants.GET_DAYSC, requestParams, new onOKJsonHttpResponseHandler<SuCaiBean>(new TypeToken<Response<SuCaiBean>>() {
        }) {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                showToast(throwable.getMessage());
            }

            @Override
            public void onSuccess(int statusCode, Response<SuCaiBean> datas) {
                if (datas.isSuccess()) {
                    if (rightPage == 1) {
                        rightList.clear();
                        rightList.addAll(datas.getData().getList());
                        right_refresh.finishRefresh();
                    } else {
                        if (datas.getData().getList().size() <= 0) {
                            showToast("已加载全部");
                            rightPage--;
                        }
                        rightList.addAll(datas.getData().getList());
                        right_refresh.finishLoadMore();
                    }
                    rightAdapter.notifyDataSetChanged();
                } else {
                    showToast(datas.getMsg());
                }
            }
        });
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {
            viewZz.performClick();
        }
    }

    @Override
    protected void lazyload() {

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this))
            EventBus.getDefault().unregister(this);
    }

    @Subscribe
    public void Event(MessageEvent messageEvent) {
        if (messageEvent != null && "share".equals(messageEvent.getMessage())) {
            item = rightList.get(messageEvent.getPosition());
            String[] datas=item.getMob_img().replace("[","").replace("]","").split(",");
            shareList.clear();
            for(int i=0;i<datas.length;i++)
                shareList.add(datas[i]);
            viewZz.setVisibility(View.VISIBLE);
            llShare.setVisibility(View.VISIBLE);
        }
    }

    PagerAdapter pagerAdapter = new PagerAdapter() {

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            // TODO Auto-generated method stub
            return arg0 == arg1;
        }

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return views.size();
        }

        @Override
        public void destroyItem(ViewGroup container, int position,
                                Object object) {
            // TODO Auto-generated method stub
            container.removeView(views.get(position));
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            // TODO Auto-generated method stub
            container.addView(views.get(position));
            return views.get(position);
        }
    };

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }
}
